import { COMPANY_TAGS, COMPANY_TYPE, CompanyStatus } from '@/pages/constant';
import {
  addFactoryApi,
  changeFactoryStatusApi,
  editFactoryApi,
  getFactoryCategoryApi,
  getFactoryImageApi,
  getFactoryListApi,
  getFactoryLocationApi,
  getFactoryVehicleApi,
} from '@/services/factory';
import useTableList from '@/utils/useTableList';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Cascader,
  Checkbox,
  Col,
  Flex,
  Form,
  Image,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  message as AntdMeaage,
  Drawer,
  InputNumber,
  Upload,
  Radio,
} from 'antd';
import React, { useState } from 'react';
import styles from './index.less';
import {
  ExclamationCircleOutlined,
  EyeFilled,
  EyeInvisibleFilled,
  FileImageOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import message from '@/utils/message';
import useEditModal from '@/utils/useEditModal';
import useCompany from '@/utils/useCompany';
import useCategory from '@/utils/useCategory';
import useAreas from '@/utils/useAreas';
import { getSinceYears } from '@/services/common';
import useVehicle from '@/utils/useVehicle';
import SelectImageButton from '@/components/SelectImageButton';
import { addVehicleApi } from '@/services/vehicle';
import { addCompanyApi } from '@/services/brand';

const Factory: React.FC = () => {
  const { allCompanyList, getList } = useCompany();
  const { allCategoryList } = useCategory();
  const { vehicles, getVehicleList } = useVehicle();
  const { loading, form, datasource, page, pageSize, total, onFinish, onPageChange } = useTableList(
    { fetchApi: getFactoryListApi },
  );
  const [selectIds, setSelectIds] = useState<any[]>([]);
  const [companyVal, setCompanyVal] = useState('');
  const { areas } = useAreas();
  const [look, setLook] = useState(false);

  const {
    loading: editLoading,
    form: editForm,
    currentData,
    setCurrentData,
    onCancel,
    onSave,
    setLoading,
  } = useEditModal({
    editApi: editFactoryApi,
    addApi: addFactoryApi,
    successCb: () => onPageChange(page),
  });

  const pictureUrl = Form.useWatch('pictureUrl', editForm);

  const changeStatus = (row: any) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定更改该条数据的状态吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        const { rsCode } = await changeFactoryStatusApi({
          ids: row.id,
          status: row.status === 2 ? 3 : 2,
        });
        if (rsCode === '00000000') {
          message.success('操作成功');
          onPageChange(page);
        }
      },
    });
  };

  const columns: ColumnsType<any> = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '公司/品牌名称',
      dataIndex: 'companyId',
      key: 'companyId',
      width: 150,
      render: (companyId: number) => {
        const company = allCompanyList.find((c) => c.value === companyId);
        return company ? company.label : '-';
      },
    },
    {
      title: '工厂名称',
      dataIndex: 'name',
      key: 'name',
      width: 250,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '省份',
      dataIndex: 'provinceName',
      key: 'provinceName',
      width: 150,
    },
    {
      title: '城市',
      dataIndex: 'cityName',
      key: 'cityName',
      width: 150,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      width: 300,
    },
    {
      title: '官网地址',
      dataIndex: 'website',
      key: 'website',
      width: 200,
    },
    {
      title: '工厂图片',
      dataIndex: 'pictureUrl',
      key: 'pictureUrl',
      width: 200,
      align: 'center',
      render: (url: string, row: any) => {
        return url ? <Image src={url} alt={row.name} width={'100%'} /> : '-';
      },
    },
    {
      title: '经纬度',
      dataIndex: 'location',
      key: 'location',
      width: 200,
      render: (location: string) => {
        if (!location) {
          return '-';
        } else {
          const [lat, lon] = location.split(',');
          return (
            <Flex vertical gap={5}>
              <div>经度：{lat}</div>
              <div>纬度：{lon}</div>
            </Flex>
          );
        }
      },
    },
    {
      title: '产能',
      dataIndex: 'productionCapacity',
      key: 'productionCapacity',
      width: 150,
    },
    {
      title: '投产时间/年',
      dataIndex: 'since',
      key: 'since',
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      key: 'memo',
      width: 200,
    },
    {
      title: '供应客户',
      dataIndex: 'customer',
      key: 'customer',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: number) => {
        if (status === 1) {
          return <Tag color="gray">待生效</Tag>;
        } else if (status === 2) {
          return <Tag color="green">生效</Tag>;
        } else {
          return <Tag color="red">失效</Tag>;
        }
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 200,
      align: 'center',
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const query: any = {
                  companyId: row.companyId,
                  type: row.type,
                  tags: row.tags || [],
                  name: row.name,
                  phone: row.phone,
                  position: [row.province, row.city],
                  address: row.address,
                  location: row.location,
                  website: row.website,
                  pictureUrl: row.pictureUrl
                    ? { filePath: row.pictureUrl, id: row.pictureId }
                    : undefined,
                  productionCapacity: row.productionCapacity,
                  since: row.since,
                  memo: row.memo,
                  customer: row.customer,
                  status: row.status,
                  id: row.id,
                  vehicleTypeIds: row.vehicleTypeIds,
                };
                const { rsCode, body } = await getFactoryCategoryApi({
                  factoryId: row.id,
                });
                if (rsCode === '00000000' && Array.isArray(body)) {
                  query.categoryIds = body.map((v) =>
                    v.categoryIdPath.split('-').filter(Boolean).map(Number),
                  );
                }
                const { rsCode: code, body: data } = await getFactoryVehicleApi({
                  factoryId: row.id,
                });
                if (code === '00000000' && Array.isArray(data)) {
                  query.vehicleTypeIds = data.map((v) => v.vehicleTypeId);
                }
                setCurrentData(query);
                setLook(false);
              }}
            >
              编辑
            </Button>
            <Button
              size="small"
              color="default"
              onClick={async () => {
                const query: any = {
                  companyId: row.companyId,
                  type: row.type,
                  tags: row.tags || [],
                  name: row.name,
                  phone: row.phone,
                  position: [row.province, row.city],
                  address: row.address,
                  location: row.location,
                  website: row.website,
                  pictureUrl: row.pictureUrl
                    ? { filePath: row.pictureUrl, id: row.pictureId }
                    : undefined,
                  productionCapacity: row.productionCapacity,
                  since: row.since,
                  memo: row.memo,
                  customer: row.customer,
                  status: row.status,
                  id: row.id,
                  vehicleTypeIds: row.vehicleTypeIds,
                };
                const { rsCode, body } = await getFactoryCategoryApi({
                  factoryId: row.id,
                });
                if (rsCode === '00000000' && Array.isArray(body)) {
                  query.categoryIds = body.map((v) =>
                    v.categoryIdPath.split('-').filter(Boolean).map(Number),
                  );
                }
                const { rsCode: code, body: data } = await getFactoryVehicleApi({
                  factoryId: row.id,
                });
                if (code === '00000000' && Array.isArray(data)) {
                  query.vehicleTypeIds = data.map((v) => v.vehicleTypeId);
                }
                setCurrentData(query);
                setLook(true);
              }}
            >
              查看
            </Button>
            <Button
              color="primary"
              size="small"
              variant="outlined"
              onClick={() => changeStatus(row)}
            >
              {row.status === 2 ? '失效' : '生效'}
            </Button>
          </Space>
        );
      },
    },
  ];

  const handelStatusByList = async (status: number) => {
    if (selectIds.length === 0) {
      AntdMeaage.warning('请选择要操作的行');
      return;
    }
    if (selectIds.some((v) => v.status === status)) {
      AntdMeaage.warning(
        `请勾选非${status === 2 ? '生效' : '失效'}的数字做${status === 2 ? '生效' : '失效'}操作`,
      );
      return;
    }
    const { rsCode } = await changeFactoryStatusApi({
      ids: selectIds.map((v) => v.id).join(','),
      status,
    });
    if (rsCode === '00000000') {
      AntdMeaage.success('操作成功');
      setSelectIds([]);
      onPageChange(page);
    }
  };

  const getLocaltion = async () => {
    if (selectIds.length === 0) {
      AntdMeaage.warning('请选择要操作的行');
      return;
    }
    const { rsCode } = await getFactoryLocationApi({
      ids: selectIds.map((v) => v.id).join(','),
    });
    if (rsCode === '00000000') {
      AntdMeaage.success('操作成功');
      setSelectIds([]);
      onPageChange(page);
    }
  };

  const matchImage = async () => {
    if (selectIds.length === 0) {
      AntdMeaage.warning('请选择要操作的行');
      return;
    }
    const { rsCode } = await getFactoryImageApi({
      ids: selectIds.map((v) => v.id).join(','),
    });
    if (rsCode === '00000000') {
      AntdMeaage.success('操作成功');
      setSelectIds([]);
      onPageChange(page);
    }
  };

  const saveCompany = async (companyName: string): Promise<number> => {
    return new Promise((resolve, reject) => {
      addCompanyApi({ name: companyName, abbreviation: companyName, status: 2 })
        .then((res) => {
          if (res.rsCode === '00000000') {
            getList();
            resolve(res.body.id);
          } else {
            reject(res.msg);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  const saveVehicle = async (names: string[]): Promise<number[]> => {
    const list = names.map((name) => {
      return new Promise<number>((resolve, reject) => {
        addVehicleApi({ name, status: 2, isElectric: 0 })
          .then((res) => {
            if (res.rsCode === '00000000') {
              resolve(res.body.id);
            } else {
              reject(res.msg);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    });
    return Promise.all(list);
  };

  const handelValue = async (v: any) => {
    setLoading(true);
    try {
      let file = null;
      const query: any = {
        id: v.id,
        name: v.name,
        type: v.type,
        tags: v.tags || [],
        phone: v.phone || '',
        address: v.address || '',
        location: v.location || '',
        website: v.website || '',
        productionCapacity: v.productionCapacity || 0,
        since: v.since || '',
        memo: v.memo || '',
        customer: v.customer || '',
        status: v.status,
        categoryIds: v.categoryIds.map((v: any) => v.at(-1)),
        province: v.position[0] || '',
        city: v.position[1] || '',
      };
      if (v.pictureUrl) {
        query.pictureId = v.pictureUrl.id;
      }
      if (v.imageFile && v.imageFile.fileList.length > 0) {
        file = v.imageFile.fileList[0].originFileObj;
      }
      if (typeof v.companyId === 'string') {
        const id = await saveCompany(v.companyId);
        if (typeof id === 'number') {
          query.companyId = id;
        }
      } else {
        query.companyId = v.companyId;
      }
      const vehicleNames = v.vehicleTypeIds?.filter((v: any) => typeof v === 'string') || [];
      const vehicleIds = v.vehicleTypeIds?.filter((v: any) => typeof v === 'number') || [];
      const ids = vehicleNames.length > 0 ? await saveVehicle(vehicleNames) : [];
      if (ids.length > 0) {
        getVehicleList();
      }
      query.vehicleTypeIds = [...ids, ...vehicleIds];
      const data = new FormData();
      if (file) {
        data.append('file', file);
      }
      data.append('requestParam', JSON.stringify(query));
      onSave(data, v.id || undefined);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  const onSubmit = () => {
    editForm
      .validateFields()
      .then((v) => {
        handelValue(v);
      })
      .catch((e) => {
        console.log(e);
      });
  };
  return (
    <PageContainer>
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form
            form={form}
            onFinish={(v: any) => {
              const other = v.other;
              const categorys = v.categoryIds;
              delete v.other;
              delete v.categoryIds;
              if (other) {
                v.locationImCompleted = other.includes(1);
                v.pictureImCompleted = other.includes(2);
              }
              if (categorys) {
                v.categoryIds = categorys.map((item: any) => item.at(-1));
              }
              onFinish(v);
            }}
            onReset={() => onFinish({})}
            labelCol={{
              span: 5,
            }}
            style={{ width: '100%' }}
          >
            <Row gutter={[20, 20]}>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="公司/品牌" name="companyId">
                  <Select
                    placeholder="请选择公司/品牌"
                    options={allCompanyList}
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="工厂名称" name="name">
                  <Input placeholder="请输入工厂名称" allowClear />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="标签" name="categoryIds">
                  <Cascader
                    placeholder="请选择分类标签"
                    options={allCategoryList}
                    allowClear
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                      children: 'children',
                    }}
                    multiple
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="状态" name="status">
                  <Select options={CompanyStatus} placeholder="请选择" allowClear />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="其他筛选" name="other">
                  <Checkbox.Group>
                    <Checkbox value={1}>经纬度未匹配</Checkbox>
                    <Checkbox value={2}>图片缺失</Checkbox>
                  </Checkbox.Group>
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={18}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button htmlType="reset" icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            columns={columns}
            dataSource={datasource}
            loading={loading}
            rowKey="id"
            scroll={{ x: 3250 }}
            title={() => (
              <Flex align="center" justify="flex-end" gap={15}>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setLook(false);
                    setCurrentData({});
                  }}
                >
                  新增
                </Button>
                <Button type="primary" icon={<EyeFilled />} onClick={() => handelStatusByList(2)}>
                  批量生效
                </Button>
                <Button
                  type="primary"
                  icon={<EyeInvisibleFilled />}
                  onClick={() => handelStatusByList(3)}
                >
                  批量失效
                </Button>
                <Button type="primary" icon={<ReloadOutlined />} onClick={getLocaltion}>
                  批量刷新经纬度
                </Button>
                <Button type="primary" icon={<FileImageOutlined />} onClick={matchImage}>
                  批量匹配图片
                </Button>
              </Flex>
            )}
            rowSelection={{
              columnWidth: 80,
              preserveSelectedRowKeys: false,
              selectedRowKeys: selectIds.map((v) => v.id),
              onChange: (_, rows) => {
                setSelectIds(rows);
              },
            }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false,
              showQuickJumper: true,
              onChange: onPageChange,
              showTotal: (total) => `共 ${total} 条数据`,
            }}
          />
        </div>
      </Row>
      <Drawer
        title={currentData?.id ? '编辑工厂' : '新增工厂'}
        width={800}
        open={!!currentData}
        maskClosable={false}
        onClose={() => {
          setCompanyVal('');
          onCancel();
        }}
        destroyOnHidden
        footer={
          <Flex align="center" justify="center" gap={30}>
            <Button onClick={onCancel}>取消</Button>
            <Button type="primary" onClick={onSubmit} loading={editLoading}>
              提交
            </Button>
          </Flex>
        }
      >
        <Form
          form={editForm}
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
          style={{ padding: '20px 0' }}
          className={styles.edit_form}
          disabled={look}
        >
          <Form.Item label="ID" name="id" hidden />
          <Form.Item
            label="公司/品牌"
            name="companyId"
            rules={[{ required: true, message: '请选择公司/品牌' }]}
          >
            <Select
              placeholder="请选择公司/品牌"
              options={
                companyVal.trim() && !allCompanyList.some((c) => c.label === companyVal.trim())
                  ? [
                      {
                        label: companyVal,
                        value: companyVal,
                      },
                      ...allCompanyList,
                    ]
                  : allCompanyList
              }
              showSearch
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              onSearch={(v) => {
                setCompanyVal(v?.trim() || '');
              }}
            />
          </Form.Item>
          <Form.Item
            label="工厂名称"
            name="name"
            rules={[{ required: true, message: '请输入工厂名称' }]}
          >
            <Input placeholder="请输入工厂名称" showCount maxLength={200} />
          </Form.Item>
          <Form.Item
            label="类型"
            name="type"
            rules={[{ required: true, message: '请选择工厂类型' }]}
            initialValue={0}
          >
            <Radio.Group options={COMPANY_TYPE} />
          </Form.Item>
          <Form.Item
            label="标签"
            name="tags"
            rules={[{ required: true, message: '请选择企业标签' }]}
            initialValue={[]}
          >
            <Checkbox.Group options={COMPANY_TAGS} />
          </Form.Item>
          <Form.Item label="联系电话" name="phone">
            <Input placeholder="请输入联系电话" showCount maxLength={20} />
          </Form.Item>
          <Form.Item label="省市区" name="position">
            <Cascader
              options={areas}
              placeholder="请选择省市区"
              fieldNames={{
                value: 'id',
                label: 'name',
                children: 'children',
              }}
              showSearch={{
                filter: (inputValue, path) =>
                  path.some((option) =>
                    option.name.toLowerCase().includes(inputValue.toLowerCase()),
                  ),
              }}
            />
          </Form.Item>
          <Form.Item label="详细地址" name="address">
            <Input.TextArea placeholder="请输入工厂详细地址" showCount maxLength={500} rows={4} />
          </Form.Item>
          <Form.Item label="经纬度">
            <Form.Item name="location" noStyle>
              <Input placeholder="请输入经纬度" showCount maxLength={200} />
            </Form.Item>
            <div className={styles.tips}>
              不填写时，后台程序会自动根据填写的地址去高德API获取，如果高德获取有误，这里也可以手动更正
            </div>
          </Form.Item>
          <Form.Item label="官网网址" name="website">
            <Input placeholder="请输入官网地址" showCount maxLength={200} />
          </Form.Item>
          <Form.Item label="工厂图片" name="pictureUrl">
            <Form.Item noStyle>
              <Space size={20} direction="vertical">
                <SelectImageButton
                  onSelect={(files) => {
                    const file = files[0];
                    editForm.setFieldsValue({
                      pictureUrl: file,
                      imageFile: undefined,
                    });
                  }}
                />
                {pictureUrl && pictureUrl.filePath && (
                  <Image src={pictureUrl.filePath} width={'100%'} />
                )}
                <Form.Item noStyle name="imageFile">
                  <Upload
                    multiple={false}
                    maxCount={1}
                    accept=".jpg,.bmp,.png,.jpeg"
                    listType="picture"
                    onChange={() => {
                      editForm.setFieldsValue({
                        pictureUrl: undefined,
                      });
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传图片</Button>
                  </Upload>
                </Form.Item>
              </Space>
            </Form.Item>
          </Form.Item>
          <Form.Item label="产能" name="productionCapacity" initialValue={0}>
            <InputNumber placeholder="请输入产能" min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="投产时间" name="since">
            <Select options={getSinceYears()} placeholder="请选择投产时间" />
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input.TextArea placeholder="请输入备注" showCount maxLength={200} rows={4} />
          </Form.Item>
          <Form.Item label="供应客户" name="customer">
            <Input.TextArea placeholder="请输入供应客户" showCount maxLength={500} rows={4} />
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
            initialValue={2}
          >
            <Select options={CompanyStatus} placeholder="请选择状态" />
          </Form.Item>
          <Form.Item
            label="标签"
            name="categoryIds"
            rules={[{ required: true, message: '请选择标签' }]}
          >
            <Cascader
              placeholder="请选择分类标签"
              options={allCategoryList}
              allowClear
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children',
              }}
              multiple
            />
          </Form.Item>
          <Form.Item label="产品/零部件" name="vehicleTypeIds">
            <Select
              options={vehicles
                .filter((v) => v.status === 2)
                .map((v) => ({
                  label: v.name,
                  value: v.id,
                }))}
              placeholder="请选择或输入产品/零部件"
              showSearch
              mode="tags"
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
            />
          </Form.Item>
        </Form>
      </Drawer>
    </PageContainer>
  );
};

export default Factory;
